//
//  SGHomeTableVC.swift
//  songguo
//
//  Created by 潘传洲 on 16/6/3.
//  Copyright © 2016年 pcz. All rights reserved.
//

import UIKit
import AFNetworking
private let ID = "Home"
class SGHomeTableVC: UIViewController {

    // 模型数组
    var homeListModels : [SGHomeListModel]?
    
    // 懒加载tableview
    lazy var tableView : UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.y = -64
        tableView.width = screenWidth
        tableView.height = screenHeight + 64
        tableView.separatorStyle = .None
        tableView.rowHeight = 245
        tableView.registerNib(UINib.init(nibName: "SGHomeTableViewCell", bundle: nil), forCellReuseIdentifier: ID)
        return tableView
    }()
    
    // 懒加载手势
    lazy var tap : UITapGestureRecognizer = {
        let tap = UITapGestureRecognizer(target: self, action:  #selector(clickNavigationBar))
        return tap
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupView()
        getData()
        
    }
    
    override func viewWillAppear(animated: Bool) {
        
        super.viewWillAppear(animated)
        
        // 给导航条添加手势
        navigationController?.navigationBar.addGestureRecognizer(tap)
        navigationController?.navigationBar.setBackgroundImage(UIImage(named: "nav_bar_bg_2x64_"), forBarMetrics: .Default)
        
        scrollViewDidScroll(tableView)
    }
}

extension SGHomeTableVC{
    // 初始化界面
    func setupView() {
        view.addSubview(tableView)
        
        let titleView = UIImageView(image: UIImage(named: "launch_title_39x18_"))
        titleView.userInteractionEnabled = true
        self.navigationItem.titleView = titleView;
        
        automaticallyAdjustsScrollViewInsets = false
        tableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0)

        navigationController?.navigationBar.shadowImage = UIImage()
    }
    
    // 网络请求
    func getData() {
        let manger = AFHTTPSessionManager()
        manger.GET("http://songguolife.com/api/home", parameters: nil, progress: nil, success:{ (task: NSURLSessionDataTask, data : AnyObject?) in
            
            let array = data as! [[String: AnyObject]]
            
            self.homeListModels = SGHomeListModel.homeListModels(array)
            self.tableView.reloadData()
            
        }) { (task : NSURLSessionDataTask?, error : NSError) in
            print(error)
        }
    }
}

// MARK: - Table view data source 数据源
extension SGHomeTableVC : UITableViewDataSource{
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return homeListModels?.count ?? 0
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(ID, forIndexPath: indexPath) as! SGHomeTableViewCell
 
        cell.item = homeListModels![indexPath.row]
        
        return cell
    }
    
}

// MARK: - Table view data delegate 代理
extension SGHomeTableVC : UITableViewDelegate{
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        var alpha =  -scrollView.contentOffset.y / 64.0 * 1.0
        
        if alpha < 0  {
            alpha = 0.01
        }
        navigationItem.titleView?.alpha = alpha
        navigationController?.navigationBar.alpha = alpha
    }
    
    // 跳转到下一个界面
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        // 移除导航条上面的手势
        navigationController?.navigationBar.removeGestureRecognizer(tap)
        let specificVC = SGSpecificTableVC()
        let item = homeListModels![indexPath.row]
        if item.type == .Activity{
            specificVC.specificModel = item.activity
        }else{
            specificVC.specificModel = item.article
        }
        navigationController?.pushViewController(specificVC, animated: true)
    }
    
    // 点击了navigationBar调用的方法
    func clickNavigationBar() {
        if tableView.contentOffset.y >= 0 {
            let row : Int = Int(tableView.contentOffset.y / tableView.rowHeight)
            let indexPath = NSIndexPath(forRow: row, inSection: 0)
            tableView(tableView, didSelectRowAtIndexPath: indexPath)
        }
    }
}